<template>
	<view class="Cart">
		<scroll-view :scroll-y="true" class="Cart_info">
			<view class="Cart_info_shop" v-for="(item,key,index) in CartList" v-if="showShop">
				<view class="Cart_list">
					<view v-for="item2 in item">
						<view v-for="(childern1,index) in item2.list">
							<view class="shop_info">
								<u-checkbox-group @change="checkboxChangeChi(childern1,key,index)">
									<u-checkbox :checked="childern1.checked" shape='circle'></u-checkbox>
								</u-checkbox-group>
								<image :src="util.imageApi+childern1.image"></image>
								<view class="shop_info_price">
									<view class="title">
										{{childern1.storeName}}
										<span
											class="span">{{childern1.storeType==='1'?'认养券':childern1.storeType==='2'?'健康分':'消费券'}}</span>
									</view>
									<view class="price_j">
										<view @click="DelNum(childern1)" class="border_left">-</view>
										<view class="border_center">{{childern1.cartNum}}</view>
										<view @click="AddNum(childern1)" class="border_right">+</view>
									</view>
									<view class="price">
										￥<font>{{childern1.price}}</font>
									</view>
									<view class="remove" @click="DelShop(childern1)">
										×
									</view>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
			<view class="address" v-if="address.realName!=''">
				<view class="address_content" @click="handleAddress">
					<view class="address_content_left">
						<view class="address_content_bottom">
							<span>{{address.provinceCityDistrict}}</span>
							<span>{{address.detail}}</span>
						</view>
						<view class="address_content_top">
							<span>{{address.realName}}</span>
							<span>{{address.phone}}</span>
						</view>
					</view>
					<view class="address_content_right">
						<span></span>
					</view>
				</view>
			</view>
			<view class="nunu"></view>
		</scroll-view>

		<view class="Bottom_info">
			<view class="Bottom_info_top">
				<view class="info_money">
					<!-- <view class="money_price">
						<span v-if="PublicPrice === ''">￥0.00</span>
						<span v-else>￥{{PublicPrice}}</span>
					</view> -->
					<view class="info_title">
						<view class="fontf">合计:</view>
						<span class="">
							<!-- <view class="" v-for="(item,index) in left_scoll" :key="index">
								{{item.cateName}}<span>￥{{priceSum['storeType'+item.id]}}</span>
							</view> -->
							<view class="fontf" v-if="priceSum.storeType1!==0">
								余额:<span>￥{{priceSum.storeType1}}</span>
							</view>
							<view class="fontf" v-if="priceSum.storeType2!==0">
								健康分:<span>￥{{priceSum.storeType2 | changeStoreType2(this.priceScore)}}</span>
							</view>
							<view class="fontf" v-if="priceSum.storeType3!==0">
								消费券:<span>￥{{priceSum.storeType3}}</span>
							</view>
						</span>
					</view>
				</view>
			</view>
			<!--#ifdef H5 -->
			<!-- <u-button type="success" shape="circle" text="结算" size="4" @click="JSPrice()"></u-button> -->
			<!--#endif-->
			<!--#ifdef MP-WEIXIN || APP-PLUS -->
			<!-- <view class="JSbutton">
				<u-button type="success" shape="circle" text="结算" size="4" @click="JSPrice()"></u-button>
			</view> -->
			<!--#endif-->

			<view class="address_btn">
				<radio-group class="rarara">
					<radio :checked="checked" @click="ChangeGo">全选</radio>
				</radio-group>
				<button type="primary" @click="JSPrice()">结算</button>
				<!-- <button type="primary">结算</button> -->
			</view>
		</view>

		<u-popup :show="show" mode="center" :round="10" class="popup">
			<view class="LoginUser">
				<view class="title_logo">
					请登录
				</view>
				<view class="button" @click="ClickGo()">
					去登陆
				</view>
			</view>
		</u-popup>
		<!-- <view class="set_up_list_background" v-if="visible">
			<view class="set_up_list_box">
				<image src="https://s1.ax1x.com/2022/05/08/O38ucj.png" mode="" @click="handleClose"></image>
				<input type="text" placeholder="请输入支付密码" v-model="payPassword" />
				<button type="primary"  @click="handleSubmit">确认</button>
			</view>
		</view> -->

		<paypass ref="yspay" @cancel="handleClose" @submit="submitpay"></paypass>
	</view>
</template>

<script>
	import paypass from "@/components/ys-paypass/ys-paypass.vue";
	import util from "@/util/index.js"
	export default {
		components: {
			paypass
		},
		data() {
			return {
				util: util,
				priceScore: 0,
				payTypeList: [],
				payPassword: "",
				visible: false,
				show: false,
				code: 0,
				CartList: [],
				checked: false,
				Keylist: [],
				PublicPrice: 0,
				OldPrice: 0,
				PublicId: '',
				setTime: -1,
				Delshow: true,
				NewList: [],
				NumberLength: 0,
				Trashiness: [],
				showShop: true,
				priceSum: {
					storeType1: 0,
					storeType2: 0,
					storeType3: 0
				},
				left_scoll: [],
				address: {
					realName: "",
					provinceCityDistrict: "",
					phone: ""
				}
			};
		},
		onPullDownRefresh() {
			setTimeout(() => {
				uni.stopPullDownRefresh()
			}, 1000)
		},
		onLoad(option) {
			// 查询健康分价格
			this.$http({
				url: '/member/selectHealthScoreNum',
				method: 'GET'
			}).then(res => {
				if (res.data.code === 200) {
					this.priceScore = res.data.data.variableValue
				}
			})
			this.$http({
				url: '/crmStoreCategory/selCrmStoreCategory',
				method: 'POST'
			}).then(res => {
				this.left_scoll = res.data.data
			})
		},

		methods: {
			handleClose() {
				this.visible = false
				this.payPassword = ""
				this.PublicId = ''
				this.PublicPrice = 0
				this.checked = false
				this.NewList = []
				this.priceSum = {
						storeType1: 0,
						storeType2: 0,
						storeType3: 0
					},
					this.SearchShop()
				// #ifdef MP-WEIXIN
				this.SearchOpenID()
				//#endif
				this.SearchShop()

			},
			handleSubmit() {
				let payType = this.payTypeList.map(item => {
					return {
						payType: item.payType,
						orderNo: item.orderNo,
						price: item.totalAmount
					}
				})
				this.$http({
					url: '/member/balanceJudgment',
					data: {
						listStr: JSON.stringify(payType),
					}
				}).then(res => {
					if (res.data.code === 200) {
						let bool = true
						res.data.data.forEach(k => {
							if (k.flag !== 0) {
								bool = false
							}
						})
						if (bool) {
							this.$refs.yspay.show();
						} else {
							uni.showToast({
								title: "余额不足，请先充值",
								icon: 'error'
							})
							setTimeout(() => {
								this.handleClose()
							}, 1000)
						}

					} else {
						uni.showToast({
							title: res.data.message,
							icon: 'error'
						})
						this.handleClose()
					}
				})
			},
			submitpay(ex) {
				let payType = this.payTypeList.map(item => {
					return item.orderNo
				})
				this.$http({
					url: '/member/balancePayment',
					data: {
						orderNo: JSON.stringify(payType),
						payPassword: ex.value,
					}
				}).then(res => {
					if (res.data.code == 200) {
						uni.showToast({
							title: '支付成功',
						})
						this.handleClose()
					} else {
						uni.showToast({
							title: res.data.message,
							icon: 'error'
						}).then(this.Passshow = true)
					}
				})
			},
			DelShop(item) {
				this.$http({
					url: '/crmStoreCart/delCrmStoreCart',
					data: {
						id: item.id
					}
				}).then(res => {
					this.SearchShop()
				})
			},
			delClick() {
				this.Delshow = !this.Delshow
			},
			JSPrice() {
				// if(this.PublicPrice === 0){
				// 	uni.showToast({
				// 		title:'您还没有选择商品',
				// 		icon:'error'
				// 	})
				// }else{
				if (this.NewList == []) {
					uni.showToast({
						title: '商品不能为空',
						icon: 'error'
					})
				} else {
					let priceSum = this.priceSum
					let data = []
					this.NewList.forEach(item => {
						let payType = ""
						let amount = item.price * item.cartNum
						let totalAmount = item.price * item.cartNum
						let processingFee = item.processingFee
						if (item.storeType === '1') {
							payType = "5"
						} else if (item.storeType === '3') {
							payType = "6"
						} else {
							payType = "7"
							let totle = item.price * item.cartNum / this.priceScore
							processingFee = totle * 0.05
							amount = Number(totle) + Number(processingFee)
						}
						data.push({
							orderSrc: '3', // 订单来源
							amount: Number(amount).toFixed(2), // 实际支付金额
							deliverMoney: item.deliverMoney, // 运费
							harvestAddressId: this.address.id, // 收货地址ID
							totalAmount: Number(totalAmount).toFixed(2), // 订单总金额
							cardId: item.id, // 购物车ID
							orderType: item.isCashoutProduct == 1 ? '3' : "0", // 订单类型
							deliveryStatus: "1", // 提货方式
							payType: payType,
							processingFee: Number(processingFee).toFixed(2)
						})
					})
					this.$http({
						url: '/crmOrder/insShoppingCrmOrder',
						data: {
							crmOrderShoppingInsertDto: JSON.stringify(data)
						},
					}).then(res => {
						if (this.NewList.length != 0) {
							if (res.data.code === 200) {
								this.payTypeList = res.data.data
								this.handleSubmit()
								// console.log(this.PublicId);
								// uni.navigateTo({
								// 	url: '/pages/qrSite/qrSite?id=' + this.PublicId
								// })
								// this.visible = true
							} else {
								uni.showToast({
									title: res.data.message,
									icon: 'error'
								})
							}
						} else {
							uni.showToast({
								title: '请选择商品',
								icon: 'error'
							})
						}
					})
				}
				// }
			},
			DelNum(item) {
				if (item.cartNum != 1) {
					item.cartNum--
					if (item.checked == true) {
						let index = this.NewList.findIndex(res => res.id == item.id)
						this.PublicPrice = this.PublicPrice - this.NewList[index].price
					}
					this.$http({
						url: '/crmStoreCart/insCrmStoreCart',
						data: {
							productId: item.productId,
							cartNum: -1
						}
					}).then(res => {
						if (res.data.code === 200 && item.checked) {
							this.priceSum['storeType' + item.storeType] -= item.price
						}
					})
				}
				// // let timer = null;
				// // if (timer) clearTimeout(timer)
				// // timer = setTimeout(() => {
				// // }, 500)
			},
			AddNum(item) {
				item.cartNum++
				if (item.checked == true) {
					let index = this.NewList.findIndex(res => res.id == item.id)
					this.PublicPrice = this.PublicPrice + this.NewList[index].price
				}
				this.$http({
					url: '/crmStoreCart/insCrmStoreCart',
					data: {
						productId: item.productId,
						cartNum: 1
					}
				}).then(res => {
					if (res.data.code === 200 && item.checked) {
						this.priceSum['storeType' + item.storeType] += item.price
					}
				})
			},
			checkboxChangeChi(item, key, index) {
				if (item.checked == false) {
					item.checked = true
					this.NewList.push(item)
					this.NumberLength = this.NewList.length
					let price
					this.NewList.forEach(item => {
						price = item.cartNum * item.price
					})
					this.PublicPrice = this.PublicPrice + price
					if (this.NewList.length > 1) {
						this.PublicId = this.PublicId + ',' + item.id
					} else {
						this.PublicId = item.id
					}
					let priceSum = item.price * item.cartNum
					this.priceSum['storeType' + item.storeType] += priceSum
				} else {
					item.checked = false
					let index = this.NewList.findIndex(res => res.id == item.id)
					this.NewList.splice(index, 1)
					this.PublicPrice = this.PublicPrice - item.price * item.cartNum
					let priceSum = item.price * item.cartNum
					this.priceSum['storeType' + item.storeType] -= priceSum
				}
				let list = []
				let CartList = Object.values(JSON.parse(JSON.stringify(this.CartList)))
				CartList.forEach(k => {
					k.forEach(i => {
						list.push(...i.list)
					})
				})
				if (this.NewList.length === list.length) {
					this.checked = true
				} else {
					this.checked = false
				}
			},
			checkboxChange(key) {
				this.CartList[key].forEach(item => {
					item.checkedAll = !item.checkedAll
					let id = ''
					if (item.checkedAll === true) {
						item.list.forEach(res => {
							res.checked = true
							let price = res.cartNum * res.price
							this.PublicPrice = this.PublicPrice + price
							id = res.id
						})
						if (this.PublicId === '') {
							this.PublicId = id
						} else {
							this.PublicId = this.PublicId + ',' + id
						}
					} else {
						item.list.forEach(res => {
							res.checked = false
							this.PublicPrice = this.PublicPrice - res.price * res.cartNum
						})
					}
				})
			},
			ChangeGo(evt) {
				let priceSum = {
					storeType1: 0,
					storeType2: 0,
					storeType3: 0
				}
				if (this.checked == false) {
					this.checked = true
					let key = []
					let storeType1 = 0
					let storeType2 = 0
					let storeType3 = 0
					this.CartList[this.Keylist[0]].forEach(item => {
						item.list.map(res => {
							this.NewList.push(res)
							res.checked = true
							key.push(res.id)
							this.PublicPrice = this.PublicPrice + res.cartNum * res.price
							priceSum['storeType' + res.storeType] += (res.cartNum * res.price)
						})
					})

					this.PublicId = key.join(',')
				} else {
					this.checked = false
					this.CartList[this.Keylist[0]].forEach(item => {
						item.list.map(res => {
							res.checked = false
							this.PublicPrice = this.PublicPrice - res.cartNum * res.price
						})
					})
					this.PublicId = ''
					this.NewList = []
				}
				this.priceSum = priceSum
			},
			SearchShop() {
				this.$http({
					url: '/crmStoreCart/selCrmStoreCart',
					method: 'POST'
				}).then(res => {
					if (res.data.code == 423) {
						this.show = true
						this.code = res.data.code
					} else if (res.data.code == 401) {
						this.show = true
						this.code = res.data.code
					} else if (res.data.code == 200) {
						this.Trashiness = res.data.data
						let obj = {}
						for (let item of res.data.data) {
							const first = item.businessName
							if (obj[first]) {
								obj[first].push({
									checkedAll: false,
									list: [item]
								})
							} else {
								obj[first] = [{
									checkedAll: false,
									list: [item]
								}]
							}
						}
						for (let item2 in obj) {
							this.Keylist.push(item2)
						}
						this.CartList = obj
					}
				})
			},
			ClickGo() {
				//#ifdef APP-PLUS || H5
				uni.navigateTo({
					url: '/pages/Applogin/Applogin'
				})
				//#endif
				//#ifdef MP-WEIXIN
				if (this.code === 423) {
					uni.navigateTo({
						url: '/pages/login/login'
					})
				} else if (this.code === 401) {
					uni.getUserProfile({
						desc: '登陆',
						success: (res) => {
							this.$http({
								url: '/MemberLogin/MemberAppletLogin',
								method: 'POST',
								data: {
									nickName: res.userInfo.nickName,
									openId: this.openId,
									avatarUrl: res.userInfo.avatarUrl,
									gender: res.userInfo.gender,
									sharer: ''
								},
							}).then(res => {
								if (res.data.code === 200) {
									uni.setStorageSync('secretKey', res.data.data);
									uni.showToast({
										title: '登陆成功',
										icon: 'success'
									})
									this.show = true
									this.SearchShop()
								} else if (res.data.code === 422) {
									uni.showToast({
										title: res.data.message,
										icon: 'error'
									})
								}
							})
						}
					})
				}
				//#endif
			},

			SearchOpenID() {
				uni.login({
					provider: 'weixin',
					success: (res) => {
						let appid = 'wx3d12b18795a512e5'
						let secret = '597c87500bf123b780c82dfa64cf205a'
						let url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' + appid +
							'&secret=' +
							secret + '&js_code=' + res.code;
						uni.request({
							url: url,
							success: (res) => {
								this.openId = res.data.openid
								uni.setStorage({
									key: 'openId',
									data: res.data.openid,
								});
							}
						})
					}
				})
			},
			handleAddress() {
				uni.navigateTo({
					url: '/pages/locationGo/locationGo'
				})
			}
		},
		onShow() {
			this.PublicId = ''
			this.PublicPrice = 0
			this.checked = false
			this.NewList = []
			this.priceSum = {
					storeType1: 0,
					storeType2: 0,
					storeType3: 0
				},
				this.SearchShop()
			// #ifdef MP-WEIXIN
			this.SearchOpenID()
			//#endif
			// let id = localStorage.getItem("userSelect")
			let id = uni.getStorageSync('userSelect')
			if (id) {
				this.$http({
					url: '/crmUserAddress/selUpdAddress',
					method: "GET",
					data: {
						id
					}
				}).then(res => {
					if (res.data.code === 200) {
						this.address = res.data.data
						localStorage.removeItem("userSelect")
					} else {
						uni.showToast({
							title: '请先填写收货地址',
							icon: 'error'
						})
					}
				})
			} else {
				this.$http({
					url: '/crmUserAddress/selCrmUserAddress',
				}).then(res => {
					if (res.data.data.length > 0) {
						let list = res.data.data.filter(item => item.isDefault == 1)
						if (list.length > 0) {
							this.address = list[0]
						} else {
							this.address = res.data.data[0]
						}

					} else {
						uni.showToast({
							title: '请先填写收货地址',
							icon: 'error'
						})
					}
				})
			}

		},
		filters: {
			changeStoreType2(val, price) {
				let totle = val / price
				let serviceCharge = totle * 0.05
				return (Number(totle) + Number(serviceCharge)).toFixed(2)
			}
		}
	}
</script>

<style lang="less">
	@import './cart.css';
</style>
